import {LOADING_MESSAGE, USER_INFO} from './localstorage/cache.service.namespace';
import { CacheService } from './localstorage/cache.service';
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler} from '@angular/common/http';
import {HttpEvent, HttpErrorResponse, HttpResponse} from '@angular/common/http';
import {Observable} from 'rxjs/internal/Observable';
import {mergeMap, catchError} from 'rxjs/operators';
import { of } from 'rxjs';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';
import { User } from 'src/domain/User';
import {MessageEvent} from '../../domain/MessageEvent';

// const BaseUrl = 'http://localhost:8080/admin';

@Injectable({
  providedIn: 'root'
})
export class HttpInterceptorServiceService implements HttpInterceptor {

  constructor(private router: Router, private messageService: NzMessageService, private cache: CacheService) { }

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    let loadingMessage = this.cache.get<MessageEvent>(LOADING_MESSAGE);
    let id = null;
    if (this.hashMessage(req,loadingMessage)) {
        id = this.messageService.loading(loadingMessage.message, { nzDuration: 0 }).messageId;
    }
    let user = this.cache.get<User>(USER_INFO);
    let token: string = '';
    if (user != null) {
      token = user.token == null ? '' : user.token;
    }
    // const url = req.url.indexOf(BaseUrl) === -1 ? BaseUrl + req.url : req.url;
    let headers = {};
    if (!this.isUpload(req)) {
        headers = {'authorization' : token,'Content-Type': 'application/json;charset=UTF-8'}
    }
    const newReq = req.clone({
      setHeaders:headers
    });
    return next.handle(newReq).pipe(
      mergeMap((event: any) => {
        if (event instanceof HttpResponse && event.status === 200) {
          return this.handleData(event,id);
        } else {
          return of(event);
        }
      }),
      catchError((err: HttpErrorResponse) => this.handleData(err,id))
    );
  }

  handleData(event: HttpResponse<any> | HttpErrorResponse,messageId): Observable<any> {
    if (messageId != null) {
      this.messageService.remove(messageId);
    }
    if (event.status === 200 && event instanceof HttpResponse) {
      const res: any = event.body;
        if (res && res.code === 708) {
          this.router.navigate(['/login']);
      } else if (res.code === 200) {
          res.success = true;
          return of(event);
      } else {
        this.messageService.warning(res.message);
        return of(event);
      }
    } else {
      this.messageService.error('网络请求失败'+event);
      return of(event);
    }
  }

  hashMessage(req: HttpRequest<any>, event: MessageEvent): boolean {
      let url = event.url;
      return req.url.indexOf(url) != -1;
  }

  isUpload(req: HttpRequest<any>): boolean {
    return req.url.indexOf('upload') != -1
  }
}
